package com.yanyeori.springaop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author chenkuan
 * @desc 日志切面
 * @date 2021/3/10 010 18:33
 * 必须要交给ioc容器管理 @Aspect 才会起作用
 */
//@Aspect
//@Component
public class LogAspectXml {

    //"execution(修饰符 返回类型 包名(..代表当前包和子包)类名.方法名(参数类型..))"
    //返回值：如果是jdk自带类型可以不用写完成整定名

    //声明切点的方式，让其他通知引用
//    @Pointcut("execution(* com.yanyeori.springaop.service..*.*(..))")
//    public void pointcut() {
//
//    }

    //前置通知
//    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println(methodName + "方法运行前LogAspectXml，参数=" + (args == null ? "" : Arrays.asList(args)));
    }

    //后置通知
//    @After("pointcut()")
    public void after(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println(methodName + "方法运行后LogAspectXml，参数=" + (args == null ? "" : Arrays.asList(args)));
    }

    //后置异常通知
//    @AfterThrowing(value = "execution(* com.yanyeori.springaop.service..*.*(..))", throwing = "ex")
    public void afterException(JoinPoint joinPoint, Exception ex) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println(methodName + "方法异常LogAspectXml，参数=" + (args == null ? "" : Arrays.asList(args)) + "，异常信息：" + ex);
    }

    //后置返回
//    @AfterReturning(value = "execution(* com.yanyeori.springaop.service..*.*(..))", returning = "returnValue")
    public void afterEnd(Object returnValue) {
        System.out.println("方法返回LogAspectXml，返回值=" + returnValue);
    }

    //环绕通知
//    @Around("pointcut()")
    public void around(ProceedingJoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        Object proceed = null;
        try {
            System.out.println("环绕-前置通知LogAspectXml，参数=" + (args == null ? "" : Arrays.asList(args)));
            //业务代码执行
            proceed = joinPoint.proceed();
            System.out.println("环绕-后置通知LogAspectXml，参数=" + (args == null ? "" : Arrays.asList(args)));
        } catch (Throwable throwable) {
            System.out.println("环绕-异常通知LogAspectXml，异常=" + throwable);
        } finally {
            System.out.println("环绕-返回通知LogAspectXml，返回=" + proceed);
        }
    }
}
